package com.best.onegous.http;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import com.best.onegous.viewutils.MyProgressDialog;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.content.Context;

public class HttpClients extends BaseModel {

	private Context context;
	private MyProgressDialog pd;

	public HttpClients(Context context) {
		super(context);
		this.context = context;
	}

	public void httpclient(final String url, RequestParams params,
			final boolean isDialog) {
		if (isDialog) {
			pd = new MyProgressDialog(context, "玩命加载中！");
			pd.show();
		}
		new AsyncHttpClient().post(url, params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] responseBody) {
				try {
					if (HttpClients.this.callback(url, new JSONObject(
							new String(responseBody)))) {

						HttpClients.this.OnMessageResponse(url, new JSONObject(
								new String(responseBody)));
					} else {
						HttpClients.this.OnMessageResponse(url, null);
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (isDialog) {
					pd.dismiss();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {

				try {
					HttpClients.this.callback(url, null);
					HttpClients.this.OnMessageResponse(url, null);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (isDialog) {
					pd.dismiss();
				}
			}
		});
	}
}
